package logs

import (
	"fmt"
	"github.com/kataras/golog"
	"runtime"
	"strings"
)

var Log *golog.Logger

func getCaller() (string, int) {
	var pcs [10]uintptr
	n := runtime.Callers(1, pcs[:])
	frames := runtime.CallersFrames(pcs[:n])

	for {
		frame, more := frames.Next()
		funcName := frame.Func.Name()

		if (!strings.Contains(frame.File, "github.com/kataras/golog") || strings.Contains(frame.File, "_examples")) &&
			funcName != "main.getCaller" &&
			funcName != "main.simpleOutput" &&
			funcName != "main.jsonOutput1" &&
			funcName != "main.jsonOutput2" {
			return frame.File, frame.Line
		}

		if !more {
			break
		}
	}

	return "?", 0
}
func JsonOutput2(l *golog.Log) bool {
	fn, line := getCaller()
	var (
		datetime = l.FormatTime()
		level    = golog.GetTextForLevel(l.Level, false)
		message  = l.Message
		source   = fmt.Sprintf("%s#%d", fn, line)
	)
	fmt.Println(datetime, level, "【"+source+"】", message)
	/*
		jsonStr := fmt.Sprintf("{\n\t\"datetime\":\"%s\",\n\t\"level\":\"%s\",\n\t\"message\":\"%s\",\n\t\"source\":\"%s\"\n}", datetime, level, message, source)
		fmt.Println(jsonStr)
	*/
	return true
}

func New(l *golog.Logger) *golog.Logger {
	if l != nil {
		Log = l
	} else {
		Log = golog.New()
	}
	return Log
}

// SetLevel sets the global log level used by the simple logger.
func SetLevel(l string) {
	Log.SetLevel(l)
}

// SetPrefix sets the prefix
func SetPrefix(s string) {
	Log.SetPrefix(s)
}

// Error logs a message at error level.
func Error(v ...interface{}) {
	Log.Error(v...)
}

// Warning logs a message at warning level.
func Warning(v ...interface{}) {
	Log.Warn(v...)
}

// Warn compatibility alias for Warning()
func Warn(v ...interface{}) {
	Log.Warn(v...)
}

// Informational logs a message at info level.
func Informational(v ...interface{}) {
	Log.Info(v...)
}

// Info compatibility alias for Warning()
func Info(v ...interface{}) {
	Log.Info(v...)
}

// Debug logs a message at debug level.
func Debug(v ...interface{}) {
	Log.Debug(v...)
}
